//
//  WmcRecognitionSingleOptionView.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/10/21.
//

import UIKit

// MARK: - [WmcRecognitionSingleOptionView]

class WmcRecognitionSingleOptionView: WmcBaseView {
    // Internal


    var selectedIndexClosure: ((Int) -> Void)?
    
    func updateData(_ data: [String], selectedIndex: Int, isEnable: Bool) {
        textList = data
        self.selectedIndex = selectedIndex
        self.isEnable = isEnable
        collectionView.reloadData()
    }

    override func makeUI() {
        addSubview(collectionView)

        collectionView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
    }

    // Private

    private lazy var textList: [String] = []

    private lazy var selectedIndex: Int = 0
    
    private lazy var isEnable: Bool = true

    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 64, height: 36)
        layout.minimumInteritemSpacing = 8
        layout.scrollDirection = .horizontal

        let view = UICollectionView(frame: self.bounds, collectionViewLayout: layout)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.showsVerticalScrollIndicator = true
        view.register(WmcRecognitionSingleOptionCell.self, forCellWithReuseIdentifier: "WmcRecognitionSingleOptionCell")
        return view
    }()
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource

extension WmcRecognitionSingleOptionView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return textList.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "WmcRecognitionSingleOptionCell", for: indexPath) as! WmcRecognitionSingleOptionCell
        if let text = textList.yp.object(at: indexPath.row) {
            let isSelected = selectedIndex == indexPath.row
            cell.updateText(text, isSelected: isSelected, isEnable: isEnable)
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        selectedIndexClosure?(indexPath.row)
        selectedIndex = indexPath.row
        collectionView.reloadData()
    }
}
